package model.schedule;

import java.util.ArrayList;
import java.util.Observable;

import model.database.CalendarWrapper;
import model.database.Database;

public class Scheduler<Auction> extends Observable {
	/**
	 * Time frame to be sceduled at each point
	 * Unit: minutes
	 */
	private final int timeFrame = 1 * 60;
	/**
	 * Time frame to back track and dubble check on every new schedule
	 * Uint: minutes
	 */
	private final int timeBackCheckOffset = 1 * 60;
	private Schedule schedule;
	private Database database;

	public Scheduler(Database database) {
		this.database = database;
	}

	public void run() {
		SchedulerThread st = new SchedulerThread();
		st.start();
	}

	private class SchedulerThread extends Thread {

		public void run() {
			while (true) {
				CalendarWrapper fromTime = new CalendarWrapper(-timeBackCheckOffset * 60 * 1000);
				CalendarWrapper toTime = new CalendarWrapper(
						timeFrame * 60 * 1000);
				// Possible Eclipse bug! Casting here is wrong! model.Auction
				// should not be neccessary.
				ArrayList<Ad> ads = (ArrayList<Ad>) database
						.getAds(fromTime, toTime);
				setChanged();
				notifyObservers(ads);

				schedule = new Schedule();
				for (Ad ad : ads) {
					// System.out.println("Adding "+auction.getEnd());
					schedule.add(ad);
				}

				setChanged();
				notifyObservers(schedule);
				
				//Sleep until it's time to create a new schedule
				setChanged();
				notifyObservers("Sleeping "+timeFrame+"m");
				try {
					Thread.sleep(timeFrame * 60 * 1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
